var OrderItem = function () {
  var template = /*html*/ `
    <div class="order-item">
      <el-form :inline="true">
        <el-form-item label="供应商:">
          <table-dealer-select v-model="order.provider" style="width:220px" :order="order" :dealer-list="dealerList" :dealer-obj="dealerObj">
          </table-dealer-select>
        </el-form-item>
        <el-form-item label="采购员:">
          <el-select size="small" v-model="titleData.purchasePeople" class="form-input">
            <el-option v-for="user in userList" :key="user.id" :value="user.id" :label="user.userName"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="币种:">
          <el-select size="small" v-model="titleData.currency" class="form-input">
            <el-option value="人民币" label="人民币"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button size="small" type="primary" @click="save" :loading="loading">生成采购单</el-button>
        </el-form-item>
      </el-form>

      <div class="orderItemTableDiv">
        <table class="orderItemTable" cellspacing="0" cellpadding="0">
          <thead>
            <tr>
              <th style="min-width:180px;">物料代码</th>
              <th style="min-width:65px;">物料名称</th>
              <th style="min-width:70px;">规格型号</th>
              <th style="min-width:35px;">单位</th>
              <th style="min-width:100px;">{{taxLabel}}单价</th>
              <th style="min-width:80px;">单价对比</th>
              <th style="min-width:80px;">税率</th>
              <th style="min-width:70px;">仓库</th>
              <th style="min-width:50px;">编号</th>
              <th style="min-width:90px;">描述</th>
              <th style="min-width:140px;">关联单号</th>
              <th style="min-width:80px;">采购数量</th>
              <th style="min-width:80px;">{{taxLabel}}金额</th>
              <th style="min-width:80px;" v-if="order.provider.isTax">税额</th>
            </tr>
          </thead>
          <tbody>
            <template v-for="(detail,deitalIndex) in order.detailList">
            <template v-for="(feed,index) in detail.feedDetailList">
              <tr :key="'row_'+deitalIndex+'_'+index">
                <template v-if="index===0">
                <td :rowspan="detail.feedDetailList.length+1">
                  <el-checkbox v-model="detail.checked" @change="checkAll(detail)">{{detail.materialCode}}</el-checkbox>
                </td>
                <td :rowspan="detail.feedDetailList.length+1">
                  {{detail.companyMaterialTableBean.materialName}}
                </td>
                <td :rowspan="detail.feedDetailList.length+1">
                  {{detail.companyMaterialTableBean.model}}
                </td>
                <td :rowspan="detail.feedDetailList.length+1">
                  {{detail.companyMaterialTableBean.unit}}
                </td>
                <td :rowspan="detail.feedDetailList.length+1">
                  <el-input size="mini" v-model="detail.unitPrice" style="width:100%;" @change="unitPriceChange(detail)"></el-input>
                </td>
                <td :rowspan="detail.feedDetailList.length+1" v-html="getRangeUnitPrice(detail)">
                  
                </td>
                <td :rowspan="detail.feedDetailList.length+1">
                  <template v-if="order.provider.isTax">
                    <el-input size="mini" v-model="detail.tax" style="width:100%" @change="taxChange(detail)">
                      <template slot="append">%</template>
                    </el-input>
                  </template>
                </td>
                <td :rowspan="detail.feedDetailList.length+1">
                  {{detail.companyMaterialTableBean.defaultWarehouse}}
                </td>
                <td :rowspan="detail.feedDetailList.length+1">
                  {{detail.companyMaterialTableBean.color}}
                </td>
                <td :rowspan="detail.feedDetailList.length+1">
                  {{detail.companyMaterialTableBean.colorDescription}}
                </td>
                </template>
                <td>
                  <el-checkbox v-model="feed.checked" @change="checkFeed(detail,feed)">{{feed.companyOrderId}}</el-checkbox>
                </td>
                <td>
                  {{feed.purchaseCount}}
                </td>
                <td>
                  {{feed.totalPrice}}
                </td>
                <td v-if="order.provider.isTax">
                  {{feed.taxPrice}}
                </td>
              </tr>
            </template>
            <tr>
              <td>合计</td>
              <td>{{getSumData(detail.feedDetailList,'purchaseCount',2)}}</td>
              <td>{{getSumData(detail.feedDetailList,'totalPrice',2)}}</td>
              <td v-if="order.provider.isTax">{{getSumData(detail.feedDetailList,'taxPrice',2)}}</td>
            </tr>
            </template>
          </tbody>
        </table>
      </div>
    </div>
  `;

  return {
    props: {
      purchaseOrder: {
        type: Object,
        required: true
      },
      dealerList: {
        type: Array,
        default: function () {
          return [];
        }
      },
      dealerObj:{
        type: Object,
        default: function () {
          return {};
        }
      }
    },
    computed: {
      userList: function () {
        var userList = this.purchaseOrder.userList;
        if (userList === null || userList === undefined) {
          userList = [];
        }
        return userList;
      },
      taxLabel: function () {
        var provider = this.order.provider;
        var isTax = provider.isTax;
        return isTax ? '含税' : '';
      }
    },
    watch: {
      purchaseOrder: function () {
        var order = _.cloneDeep(this.purchaseOrder);
        this.initOrder(order);
        this.order = order;
      }
    },
    data: function () {
      var order = _.cloneDeep(this.purchaseOrder);
      this.initOrder(order);
      return {
        loading: false,
        order: order,
        titleData: {
          purchasePeople: '',
          currency: '人民币'
        }
      };
    },
    methods: {
      initOrder: function (order) {
        var detailList = order.detailList;
        for (var i = 0; i < detailList.length; i++) {
          var detail = detailList[i];
          if (detail.tax === null || detail.tax === 0) {
            detail.tax = 13;
          }

          var count = detail.companyMaterialTableBean.count;
          var useCount = detail.companyMaterialTableBean.useCount;
          useCount = count - useCount;
          detail.useCount = useCount;

          var unitPrice = detail.companyMaterialTableBean.unitPrice;
          detail.unitPrice = unitPrice;

          detail.checked = false;

          var feedDetailList = detail.feedDetailList;
          for (var j = 0; j < feedDetailList.length; j++) {
            var feed = feedDetailList[j];
            var purchaseCount = feed.purchaseCount;
            feed.purchaseCountRes = purchaseCount;
            feed.totalPrice = this.getTotalPrice(detail, feed);
            feed.taxPrice = this.getTaxPrice(detail, feed, order);
            feed.checked = false;
          }
        }
      },

      unitPriceChange: function (detail) {
        var unitPrice = detail.unitPrice;
        if (typeof unitPrice === 'string') {
          unitPrice = Number(unitPrice);
          if (_.isNaN(unitPrice) || unitPrice < 0) {
            this.$alert('请输入正确的单价', '信息');
            detail.unitPrice = detail.companyMaterialTableBean.unitPrice;
          } else {
            detail.unitPrice = _.round(unitPrice, 2);
          }
        }

        var feedDetailList = detail.feedDetailList;
        for (var i = 0; i < feedDetailList.length; i++) {
          var feed = feedDetailList[i];
          var totalPrice = this.getTotalPrice(detail, feed);
          feed.totalPrice = totalPrice;

          var taxPrice = this.getTaxPrice(detail, feed);
          feed.taxPrice = taxPrice;
        }
      },

      taxChange: function (detail) {
        var tax = detail.tax;
        if (typeof tax === 'string') {
          tax = Number(tax);
          if (_.isNaN(tax)) {
            this.$alert('请输入正确的税率', '信息');
            detail.tax = 13;
          } else {
            if (tax < 0 || tax > 100) {
              this.$alert('税率的范围为0-100', '信息');
              tax = 13;
            }
            detail.tax = _.round(tax, 0);
          }
        }

        var feedDetailList = detail.feedDetailList;
        for (var i = 0; i < feedDetailList.length; i++) {
          var feed = feedDetailList[i];
          var taxPrice = this.getTaxPrice(detail, feed);
          feed.taxPrice = taxPrice;
        }
      },

      purchaseCountChange: function (detail) {
        var feedDetailList = detail.feedDetailList;
        //相同物料投料单占用数量
        var materialUseCount = detail.companyMaterialTableBean.materialUseCount;
        if (materialUseCount === null) {
          materialUseCount = 0;
        }
        //关联数量
        var relationCount = detail.companyMaterialTableBean.relationCount;
        if (relationCount === null || relationCount < 0) {
          relationCount = 0;
        }
        relationCount += materialUseCount;
        //未入库数量
        var notInCount = detail.companyMaterialTableBean.notInCount;
        if (notInCount === null) {
          notInCount = 0;
        }
        //库存数量
        var materialCount = detail.companyMaterialTableBean.count;
        if (materialCount === null) {
          materialCount = 0;
        }

        for (var i = 0; i < feedDetailList.length; i++) {
          var feed = feedDetailList[i];
          var count = feed.purchaseCountRes;
          var feedOutCount = feed.feedOutCount;
          //得到在车间的数量
          var receiveCount = feed.receiveCount;
          if (receiveCount === null) {
            receiveCount = 0;
          }
          //未审核数量
          var usePurchseNotApprovelCount = feed.usePurchseNotApprovelCount;
          if (usePurchseNotApprovelCount === null) {
            usePurchseNotApprovelCount = 0;
          }

          if (!feed.checked) {
            feed.purchaseCount = count;
            continue;
          }
          if (materialCount + notInCount - relationCount <= 0) {
            if (feedOutCount != null && feedOutCount > 0) {
              feed.purchaseCount = count - feedOutCount;
            } else {
              feed.purchaseCount = count;
            }
            continue;
          } else {
            if (feedOutCount != null && feedOutCount > 0) {
              feed.purchaseCount = count - feedOutCount;
            } else {
              feed.purchaseCount = count;
            }
          }
          var purchaseCount = feed.purchaseCountRes - feedOutCount;

          //计算采购数 投料数 - (库存数量+未入库-关联)-在车间的数量-未审核数量
          if (materialCount + notInCount - relationCount - receiveCount - usePurchseNotApprovelCount > purchaseCount) {
            feed.purchaseCount = 0;
            relationCount += purchaseCount;
          } else {
            purchaseCount = purchaseCount - (materialCount + notInCount - relationCount - receiveCount - usePurchseNotApprovelCount);
            feed.purchaseCount = purchaseCount;
            relationCount += count - feed.purchaseCount;
          }

          //计算采购数 投料数 - (库存数量+未入库-关联)
          if (materialCount + notInCount - relationCount > purchaseCount) {
            feed.purchaseCount = 0;
            relationCount += purchaseCount;
          } else {
            purchaseCount = purchaseCount - (materialCount + notInCount - relationCount);
            feed.purchaseCount = purchaseCount;
            relationCount += count - feed.purchaseCount;
          }
        }

        for (var i = 0; i < feedDetailList.length; i++) {
          var feed = feedDetailList[i];
          var totalPrice = this.getTotalPrice(detail, feed);
          feed.totalPrice = totalPrice;

          var taxPrice = this.getTaxPrice(detail, feed);
          feed.taxPrice = taxPrice;
        }
      },

      checkAll: function (detail) {
        var checkAll = detail.checked;
        var feedDetailList = detail.feedDetailList;
        for (var i = 0; i < feedDetailList.length; i++) {
          var feed = feedDetailList[i];
          feed.checked = checkAll;
        }
        this.purchaseCountChange(detail);
      },

      checkFeed: function (detail, feed) {
        var checkAll = true;
        var feedDetailList = detail.feedDetailList;
        for (var i = 0; i < feedDetailList.length; i++) {
          var feed = feedDetailList[i];
          if (!feed.checked) {
            checkAll = false;
            break;
          }
        }
        detail.checked = checkAll;
        this.purchaseCountChange(detail);
      },

      save: function () {
        var titleData = this.titleData;
        var purchasePeople = titleData.purchasePeople;
        if (purchasePeople === '') {
          this.$alert('请选择采购人', '信息');
          return;
        }
        var order = this.order;
        var provider = order.provider;
        var postData = {
          purchasePeople: purchasePeople,
          providerName: provider.name,
          agent: provider.id,
          agentSource: provider.source,
          currency: titleData.currency,
          type: 1,
          status: 0
        };

        var orderDetailList = order.detailList;
        var detailList = [];
        for (var i = 0; i < orderDetailList.length; i++) {
          var detail = orderDetailList[i];
          var feedDetailList = detail.feedDetailList;
          feedDetailList = _.filter(feedDetailList, {
            checked: true
          });
          if (feedDetailList.length <= 0) {
            continue;
          }

          var detailObj = this.getPostOrderDetail(detail, feedDetailList);
          if (detailObj === null) {
            return;
          }
          detailList.push(detailObj);
        }

        if (detailList.length === 0) {
          this.$alert('请选择要生成采购单的订单', '信息');
          return;
        }
        postData.detailList = detailList;

        this.loading = true;
        var self = this;
        ajaxRequest('purchaseOrder/savePurchaseOrder', {
          purchase: JSON.stringify(postData)
        }).then(function () {
          self.loading = false;
          self.$alert('生成采购单成功', '信息');
          self.$emit('save-success');
        }).catch(function () {
          self.loading = false;
        });
      },

      getPostOrderDetail: function (detail, feedDetailList) {
        var unitPrice = detail.unitPrice;
        if (unitPrice === '') {
          this.$alert('请输入单价', '信息');
          return null;
        }

        var tax = detail.tax;
        var isTax = this.order.provider.isTax;
        if (isTax && tax === '') {
          this.$alert('请输入税率', '信息');
          return null;
        }

        var detailObj = {
          materialCode: detail.materialCode,
          materialName: detail.companyMaterialTableBean.materialName,
          model: detail.companyMaterialTableBean.model,
          color: detail.companyMaterialTableBean.color,
          tax: isTax ? tax : 0,
          price: detail.unitPrice,
        };

        var totalCount = 0;
        feedDetailList = _.map(feedDetailList, function (feed) {
          var purchaseCount = feed.purchaseCount;
          totalCount += purchaseCount;
          return {
            orderId: feed.orderId,
            purchaseCount: purchaseCount,
            lineNo: feed.lineNo,
            materialType: feed.materialType,
            materialFactory: feed.materialFactory,
            feedDetailId: feed.id
          };
        });
        detailObj.purchaseCount = totalCount;
        detailObj.feedDetailList = feedDetailList;
        return detailObj;
      },

      getTotalPrice: function (detail, feed) {
        var unitPrice = detail.unitPrice;
        var purchaseCount = feed.purchaseCount;
        if (typeof unitPrice === 'string') {
          unitPrice = Number(unitPrice);
          if (_.isNaN(unitPrice)) {
            unitPrice = 0;
          }
        }
        return _.round(unitPrice * purchaseCount, 2);
      },

      getTaxPrice: function (detail, feed, order) {
        if (order === undefined) {
          order = this.order
        }
        if (!order.provider.isTax) {
          return null;
        }

        var tax = detail.tax;
        if (typeof tax === 'string') {
          tax = Number(tax);
          if (_.isNaN(tax)) {
            tax = 13;
          }

          if (tax < 0 || tax > 100) {
            tax = 13;
          }
        }

        var totalPrice = feed.totalPrice;
        return _.round(totalPrice * tax / 100, 2);
      },

      getSumData: function (data, field, precision) {
        if (field === 'taxPrice') {
          if (!this.order.provider.isTax) {
            return null;
          }
        }

        if (precision === undefined) {
          precision = 2;
        }
        var sum = _.sumBy(data, function (d) {
          var value = _.get(d, field);
          if (value === null || value === undefined) {
            return 0;
          }

          if (typeof value === 'string') {
            value = Number(value);
            if (_.isNaN(value)) {
              value = 0;
            }
          }
          return value;
        });
        return _.round(sum, precision);
      },

      getRangeUnitPrice: function (detail) {
        var unitPrice = detail.unitPrice;
        if (unitPrice === '') {
          return '';
        }

        if (typeof unitPrice === 'string') {
          unitPrice = Number(unitPrice);
          if (_.isNaN(unitPrice)) {
            return '';
          }
        }

        if (unitPrice < 0) {
          return '';
        }

        var resPrice = detail.companyMaterialTableBean.unitPrice;
        if (unitPrice === resPrice) {
          return '';
        }

        var rate = (unitPrice - resPrice) / resPrice;
        rate = _.round(rate * 100, 2);
        if (_.isNaN(rate)) {
          return '';
        }
        return `<span style="color:${rate<0?"#ff0000":"#409EFF"};">${rate}%</span>`;
      }
    },
    components: {
      TableDealerSelect: TableDealerSelect
    },
    template: template
  }
}();